from django.contrib.auth.models import User
from django.db import models

from utils.modelsMixin import ModelSetMixin


class UserDetail(models.Model):
    SEX_CHOICE = (
        (0, '女'),
        (1, '男')
    )
    avatar = models.TextField(null=True, blank=True, verbose_name='头像')
    phone = models.CharField(max_length=11, unique=True, null=True, blank=True, verbose_name='电话')
    age = models.SmallIntegerField(null=True, blank=True, verbose_name='年龄')
    sex = models.SmallIntegerField(null=True, blank=True, verbose_name='性别', choices=SEX_CHOICE)
    birthday = models.DateTimeField(null=True, blank=True, verbose_name='生日')

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    default_address = models.ForeignKey('Address', verbose_name='默认收货地址', on_delete=models.SET_NULL, null=True,
                                        blank=True)

    class Meta:
        db_table = 'detail'
        verbose_name = '用户详情'
        verbose_name_plural = verbose_name


class Area(models.Model):
    name = models.CharField(max_length=20, verbose_name='名称')
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL, verbose_name='上级行政区')

    class Meta:
        db_table = 'area'
        verbose_name = '行政区'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.id}-{self.name}'


class Address(ModelSetMixin):
    name = models.CharField(max_length=40, verbose_name='地址分类')  # 家？公司？其他？
    # models.PROTECT防止删除被引用对象。因为‘省市区’反向管理器都是同一个，因此为了区分，需要设置关联名称related_name
    province = models.ForeignKey(Area, verbose_name='省', on_delete=models.PROTECT, related_name='province_address')
    city = models.ForeignKey(Area, verbose_name='市', on_delete=models.PROTECT, related_name='city_address')
    district = models.ForeignKey(Area, verbose_name='区', on_delete=models.PROTECT, related_name='district_address')
    place = models.CharField(max_length=40, verbose_name='详细地址')
    receiver = models.CharField(max_length=40, verbose_name='收货人')
    phone = models.CharField(max_length=11, verbose_name='手机号')

    user = models.ForeignKey(User, verbose_name='用户', on_delete=models.CASCADE)

    class Meta:
        ordering = ['-u_time']
        db_table = 'address'
        verbose_name = '收货地址'
        verbose_name_plural = verbose_name
